/*
 * Copyright 2011 es-planning Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.arctos.ursus.extensions.net.example.echo.tcp.client;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;

import jp.arctos.ursus.extension.net.Config;
import jp.arctos.ursus.extension.net.SendRequest;
import jp.arctos.ursus.extension.net.SocketService;
import jp.arctos.ursus.extension.net.SocketSessionHandler;
import jp.arctos.ursus.thread.RealtimeThreadParameters;

public class TCPEchoClient {
    private static final int CONNECT_RETRY = 10;

    private void echo() throws Exception {
        SocketAddress serverAddress = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 10003);
        SocketAddress clientAddress = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0);

        // ソケットサービス作成
        // スレッドはjavax.realtime.RealtimeThreadのデフォルト
        RealtimeThreadParameters threadParameters = new RealtimeThreadParameters();
        Config config = new Config();
        config.setRealtimeThreadParameters(threadParameters);
        SocketService service = new SocketService(config);

        // 非同期イベントを扱うイベントハンドラを設定
        service.setEventHandler(new SocketEchoClientEventHandler());

        // サーバに接続し、セッションハンドラを取得
        // 接続できなかった場合は、1秒毎にリトライする
        SocketSessionHandler sessionHandler = null;
        for (int retry = 0; retry < CONNECT_RETRY; retry++) {
            try {
                sessionHandler = service.connect(serverAddress, clientAddress);
                System.out.println("Connected.");
                break;

            } catch (IOException e) {
                System.out.println("Failed to connect.");

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {}
            }
        }

        if (sessionHandler != null) {
            // 送信メッセージを編集
            byte[] bytes = "echo-request".getBytes();
            ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
            buffer.put(bytes);
            buffer.flip();
            SendRequest request = new SendRequest(buffer);

            // メッセージを送信
            sessionHandler.send(request);
            System.out.println("Sent request.");

            try {
                Thread.sleep(30000);
            } catch (InterruptedException ie) {}

            // 30秒後にセッションをクローズ
            sessionHandler.close();
        }

        // サービスをシャットダウン
        service.shutdown();
    }

    public static void main(String[] args) throws Exception {
        TCPEchoClient client = new TCPEchoClient();
        client.echo();
    }
}
